package com.example.Administrator.shoujiweishi.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;

import com.example.Administrator.shoujiweishi.MyApplication;
import com.example.Administrator.shoujiweishi.db.MobileInfoDao;
import com.example.Administrator.shoujiweishi.vo.Contact;
import com.example.Administrator.shoujiweishi.vo.MobileInfo;

import org.apache.commons.io.FileUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zzsgz on 2017/4/23.
 */
//普通JAVA类，是没有上下文
public class MyUtil {
    //返回共享首选项对象
    public static SharedPreferences getSharedPre(){
         //获取上下文  再获取共享首选项
        return  MyApplication.getContext().getSharedPreferences("loginnew", Context.MODE_PRIVATE);


    }

    public static boolean isSDCard(){
        String state = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(state)){
            return true;
        }else{
            return false;
        }
    }

    //能否读写 能写就写入SD卡，不能就写手机存储中
    public static File getPath(){
        File path = null;
        if(isSDCard()){
            path = Environment.getExternalStorageDirectory();
        }else{
            path = Environment.getDownloadCacheDirectory();
        }

        return path;
    }
    public static Intent getInstallIntent(File file){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        return intent;
    }

    public static String gethttp(String path) throws IOException {
        String json = null;
        URL url=new URL(path);
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        InputStream im=conn.getInputStream();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(im));
        json=bufferedReader.readLine();
        im.close();
        return json;
    }
    public static void copyFileToMobile(Context context,String dbname) throws IOException {
        URL url=context.getClass().getClassLoader().getResource("assets/"+dbname);//资源文件夹中的数据库路径
        String dbfile="/data/data/"+MyApplication.getContext().getPackageName()+"/databases";//导入路径
        File fileMobiledir=new File(dbfile);//目的路径
        if (!fileMobiledir.exists()){//如果资源不为空
            fileMobiledir.mkdirs();//创建文件夹的方法
        }
        File dbfileMobile=new File(fileMobiledir+"/"+dbname);//创建文件的名字
        if (!dbfileMobile.exists()){//如果资源不为空
            dbfileMobile.createNewFile();//创建文件的方法
        }
        FileUtils.copyURLToFile(url,dbfileMobile);//运行
    }

    public static List<Contact> getAllContact(){
        List<Contact> list=new ArrayList<Contact>();

        ContentResolver contentProvider= MyApplication.getContext().getContentResolver();//取得ContentResolver对象
        Cursor cursor=contentProvider.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
        if (cursor!=null){
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                //取得联系人名字
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                //取得电话号码
                int num=cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String phonenum =null;
                if (num>0){
                    phonenum=getPhoneNumById(id);
                String addre=null;
                addre=getAddressById(phonenum);
                Contact contact=new Contact(id,name,phonenum,addre);
                list.add(contact);
                }
            }

            cursor.close();
        }else if(!cursor.moveToFirst()){

        }else{

        }
        return list;

    }

    private static String getAddressById(String phonenum) {
        MobileInfo mobileInfo=null;
        String newtel=phonenum.replace(" ","").replace("-","");
        String telnum=null;
        if (newtel.length()==11&&newtel.matches("^1[34578]\\d{9}$")){
            telnum=newtel.substring(0,7);
            mobileInfo=MyApplication.getMobiledaoSession().getMobileInfoDao().queryBuilder()
                    .where(MobileInfoDao.Properties.MobileNumber.eq(telnum))
                    .distinct()
                    .unique();
        }else{
            int lenght=newtel.length();
            switch (lenght){
                case 10 :
                    mobileInfo=getMobileInfo(newtel,3);
                    break;
                case 11 :
                    mobileInfo=getMobileInfo(newtel,3);
                    String add=mobileInfo.getMobileArea();
                    if (mobileInfo==null){
                        mobileInfo=getMobileInfo(newtel,4);
                    }
                    break;
                case 12:
                    mobileInfo=getMobileInfo(newtel,4);
                    break;
                default:
            }
        }
        /*String talnum=phonenum.replace(" ","").replace("-","").substring(0,7);
        MobileInfo mobileinfo=MyApplication
                .getMobiledaoSession()
                .getMobileInfoDao()
                .queryBuilder()
                .where(MobileInfoDao.Properties.MobileNumber.eq(talnum))
                .distinct()
                .unique();

        return mobileinfo.getMobileArea();*/

        try {//如果空指针异常，则处理
            mobileInfo.getMobileArea();
        }catch (NullPointerException e){
            return "未知";
        }
            return mobileInfo.getMobileArea();



    }

    public static MobileInfo getMobileInfo(String newtel,int num){
        MobileInfo mobileInfo=MyApplication.getMobiledaoSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.AreaCode.eq(newtel.substring(0,num))).limit(1).distinct().unique();
        return mobileInfo;
    }

    private static String getPhoneNumById(int id) {
        String talnum=null;
        ContentResolver contentResolver= MyApplication.getContext().getContentResolver();//取得ContentResolver对象
        Cursor cursor=contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                ,new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}
                ,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?"
                ,new String[]{id+""}
                ,null);
        if (cursor!=null){
            if (cursor.moveToNext()){
                talnum=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        }
        return talnum;
    }
}
